import React, { useState, useEffect } from 'react';
import { Row, Col, Statistic, Tabs } from 'antd';
import ReactECharts from 'echarts-for-react';
import { getStockKLines, getStockFenshi } from '../../service/apis/quotation';
import { max } from 'lodash';

const { TabPane } = Tabs;

interface KLinesProps {
  code: string;
}

const KLines: React.FC<KLinesProps> = ({ code }) => {
  const [stockData, setStockData] = useState([]);
  const [timeLineData, setTimeLineData] = useState([]);
  const [currentData, setCurrentData] = useState({});
  const [activeTab, setActiveTab] = useState('kline'); // 默认显示日K线

  useEffect(() => {
    // 清空数据
    setStockData([]);
    setTimeLineData([]);
    setCurrentData({});
    setActiveTab('kline');

    // 默认加载日K线数据
    getStockKLines({ code }).then((data) => {
      setStockData(data);
      setCurrentData(data[data.length - 1]);
    });
  }, [code]);

  const handleTabChange = (key) => {
    setActiveTab(key);
    if (key === 'kline') {
      getStockKLines({ code }).then((data) => {
        setStockData(data);
        setCurrentData(data[data.length - 1]);
      });
    } else if (key === 'timeline') {
      getStockFenshi({ code }).then((data) => {
        setTimeLineData(data);
        // setCurrentData(data[data.length - 1]);
      });
    }
  };

  const getKLineOption = () => {
    const dates = stockData.map(item => item.jyr);
    const values = stockData.map(item => [item.open, item.close, item.low, item.high]);
    const volumes = stockData.map(item => item.volume);

    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
        formatter: (params) => {
          const index = params[0].dataIndex;
          setCurrentData(stockData[index]);
          return `
            日期: ${stockData[index].jyr}<br/>
            价格: ${stockData[index].close}<br/>
            成交额: ${Number(stockData[index].money / 100000000).toFixed(2)}亿<br/>
            换手率: ${stockData[index].hsl}%<br/>
            涨幅: ${stockData[index].inc}%
          `;
        },
      },
      xAxis: [
        {
          type: 'category',
          data: dates,
          scale: true,
          boundaryGap: false,
          axisLine: { show: false },
          axisLabel: { show: false },
          splitLine: { show: false },
          min: 'dataMin',
          max: 'dataMax',
        },
        {
          type: 'category',
          gridIndex: 1,
          data: dates,
          scale: true,
          boundaryGap: false,
          axisLine: { show: false },
          axisLabel: { show: false },
          splitLine: { show: false },
          min: 'dataMin',
          max: 'dataMax',
        },
      ],
      yAxis: [
        {
          scale: true,
          splitArea: {
            show: true,
          },
        },
        {
          scale: true,
          gridIndex: 1,
          splitNumber: 2,
          axisLabel: { show: false },
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false },
        },
      ],
      grid: [
        {
          left: '10%',
          right: '8%',
          height: '50%',
        },
        {
          left: '10%',
          right: '8%',
          top: '63%',
          height: '16%',
        },
      ],
      dataZoom: [
        {
          type: 'slider',
          xAxisIndex: [0, 1],
          start: 90,
          end: 100,
          handleIcon: 'M8.2,13.2c-0.4,0-0.8-0.2-1.1-0.4L1.4,7.5C1,7.1,1,6.5,1.4,6.1l5.7-5.3c0.6-0.6,1.5-0.6,2.1,0l5.7,5.3c0.4,0.4,0.4,1,0,1.4l-5.7,5.3C9,13,8.6,13.2,8.2,13.2z',
          handleSize: '80%',
          handleStyle: {
            color: '#fff',
            shadowBlur: 3,
            shadowColor: 'rgba(0, 0, 0, 0.6)',
            shadowOffsetX: 2,
            shadowOffsetY: 2,
          },
        },
      ],
      series: [
        {
          name: 'K线',
          type: 'candlestick',
          data: values,
          itemStyle: {
            color: '#ec0000',
            color0: '#00da3c',
            borderColor: '#8A0000',
            borderColor0: '#008F28',
          },
        },
        {
          name: '成交量',
          type: 'bar',
          xAxisIndex: 1,
          yAxisIndex: 1,
          data: volumes.map((vol, index) => ({
            value: vol,
            itemStyle: {
              color: stockData[index].close > stockData[index].open ? '#00da3c' : '#ec0000',
            },
          })),
        },
      ],
    };
  };

  const getTimeLineOption = () => {
    const times = timeLineData.map(item => item.curTime);
    // const times = timeLineData.map(item => {
    //   const date = new Date(item.curTime * 1000); // 乘以1000转换为毫秒
    //   const hours = date.getHours();
    //   const minutes = date.getMinutes();
    //   const seconds = date.getSeconds();
    //   return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    // });
    const incs = timeLineData.map(item => item.inc);
    const volumes = timeLineData.map(item => item.volume);

    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
        formatter: (params) => {
          const index = params[0].dataIndex;
          const data = timeLineData[index];
          return `
            时间: ${data.curTime}<br/>
            价格: ${data.curPrice}<br/>
            涨幅: ${data.inc}<br/>
            成交量: ${data.volume}
          `;
        },
      },
      xAxis: [
        {
          type: 'category',
          data: times,
          scale: true,
          boundaryGap: false,
          axisLine: { show: false },
          axisLabel: { show: false },
          splitLine: { show: false },
          min: 'dataMin',
          max: 'dataMax',
        },
        {
          type: 'category',
          gridIndex: 1,
          data: times,
          scale: true,
          boundaryGap: false,
          axisLine: { show: false },
          axisLabel: { show: false },
          splitLine: { show: false },
          min: 'dataMin',
          max: 'dataMax',
        },
      ],
      yAxis: [
        {
          position: 'left',
          axisLine: {
            show: true,
          },
          scale: true,
          // splitArea: {
          //   show: true,
          // },
          min:currentData.lowLimit !=null?currentData.lowLimit:-10,
          max:currentData.highLimit !=null?currentData.highLimit:10,
        },
        {
          scale: true,
          gridIndex: 1,
          splitNumber: 2,
          axisLabel: { show: false },
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false },
        },
      ],
      grid: [
        {
          left: '10%',
          right: '8%',
          height: '50%',
        },
        {
          left: '10%',
          right: '8%',
          top: '63%',
          height: '16%',
        },
      ],
      series: [
        {
          name: '分时线',
          type: 'line',
          data: incs,
          itemStyle: {
            color: 'gray',
          },
        },
        {
          name: '成交量',
          type: 'bar',
          xAxisIndex: 1,
          yAxisIndex: 1,
          data: volumes.map((vol, index) => ({
            value: Math.abs(vol),
            itemStyle: {
              color: vol > 0 ? '#00da3c' : '#ec0000',
            },
          })),
        },
      ],
    };
  };

  return (
    <div>
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Row gutter={[16, 16]}>
            <Col span={4}>
              <Statistic title="股票代码" value={currentData.code} valueStyle={{ color: currentData.inc > 0 ? '#cf1322' : '#3f8600' }} />
            </Col>
            <Col span={4}>
              <Statistic title="股票名称" value={currentData.name} valueStyle={{ color: currentData.inc > 0 ? '#cf1322' : '#3f8600' }} />
            </Col>
            <Col span={4}>
              <Statistic title="涨幅" value={Number(currentData.inc).toFixed(2)} suffix="%" valueStyle={{ color: currentData.inc > 0 ? '#cf1322' : '#3f8600' }} />
            </Col>
            <Col span={4}>
              <Statistic title="总市值" value={Number(currentData.tValue / 100000000).toFixed(2)} suffix="亿" />
            </Col>
            <Col span={4}>
              <Statistic title="流通市值" value={Number(currentData.fValue / 100000000).toFixed(2)} suffix="亿" />
            </Col>
            <Col span={4}>
              <Statistic title="成交额" value={Number(currentData.money / 100000000).toFixed(2)} suffix="亿" />
            </Col>
            <Col span={4}>
              <Statistic title="市盈率" value={Number(currentData.syl).toFixed(2)} />
            </Col>
            <Col span={4}>
              <Statistic title="市净率" value={Number(currentData.sjl).toFixed(2)} />
            </Col>
            <Col span={4}>
              <Statistic title="换手率" value={Number(currentData.hsl).toFixed(2)} suffix="%" valueStyle={{ color: currentData.inc > 0 ? '#cf1322' : '#3f8600' }} />
            </Col>
          </Row>
          <Tabs defaultActiveKey="kline" activeKey={activeTab} onChange={handleTabChange}>
            <TabPane tab="日K线" key="kline">
              <ReactECharts option={getKLineOption()} style={{ height: '600px' }} />
            </TabPane>
            <TabPane tab="分时线" key="timeline">
              <ReactECharts option={getTimeLineOption()} style={{ height: '600px' }} />
            </TabPane>
          </Tabs>
        </Col>
      </Row>
    </div>
  );
};

export default KLines;